<template>
  <div class="content">
    <div class="content_title">分院信息</div>
    <div v-loading="loading">
      <div class="main_content">
        <div class="main_content_left">
          <el-image
            class="branch_pic"
            fit="contain"
            :src="
              branchInfo.branchPic
                ? branchInfo.branchPic
                : require('@/assets/images/branch.png')
            "
            :preview-src-list="[
              branchInfo.branchPic
                ? branchInfo.branchPic
                : require('@/assets/images/branch.png'),
            ]"
            alt="加载失败"
          ></el-image>
        </div>
        <div class="main_content_right">
          <div class="content_lebal">
            <div class="title">分院名称：</div>
            <div class="content_value">
              {{ branchInfo.branchName }}
            </div>
          </div>
          <div class="content_lebal">
            <div class="title">联系人：</div>
            <div class="content_value">
              {{ branchInfo.principal ? branchInfo.principal : '--' }}
            </div>
          </div>
          <div class="content_lebal">
            <div class="title">手机号码：</div>
            <div class="content_value">
              {{ branchInfo.tel ? branchInfo.tel : '--' }}
            </div>
          </div>
          <div class="content_lebal">
            <div class="title">地址：</div>

            <div class="content_value">
              {{ branchInfo.address ? branchInfo.address : '--' }}
            </div>
          </div>
          <div class="content_lebal">
            <div class="title">分院简介：</div>
            <div class="content_textarea" v-html="renderedText"></div>
          </div>
        </div>
      </div>
      <div style="margin-top: 20px">
        <el-button
          v-preventReClick
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAddAdmin"
        >添加管理员
        </el-button
        >
        <el-table
          v-loading="adminloading"
          style="margin-top: 20px"
          :data="adminList"
        >
          <el-table-column
            align="center"
            property="nickName"
            label="姓名"
          ></el-table-column>
          <el-table-column
            align="center"
            property="account"
            label="账号"
          ></el-table-column>
          <el-table-column
            align="center"
            property="phoneNumber"
            label="手机号码"
          >
            <!-- 手机号脱敏 -->

            <template slot-scope="scope">
              {{ scope.row.phoneNumber | regPhone }}
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <!-- // 0.启用 1.禁用 2.待提交 3.待审核 4.已驳回 5.已到期 -->
              <el-tag type="success" v-if="scope.row.status == 0">启用</el-tag>
              <el-tag type="danger" v-if="scope.row.status == 1">禁用</el-tag>
              <el-tag v-if="scope.row.status == 2">待提交</el-tag>
              <el-tag type="warning" v-if="scope.row.status == 3"
              >待审核
              </el-tag
              >
              <el-tag type="danger" v-if="scope.row.status == 4">已驳回</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                v-preventReClick
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleAdminUpdate(scope.row)"
              >编辑
              </el-button
              >
              <el-button
                v-preventReClick
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleAdminSwitch(scope.row)"
              >{{ scope.row.status == 0 ? '停用' : '启用' }}
              </el-button
              >
              <el-button
                v-preventReClick
                v-if="scope.row.status == 1"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleAdminDelete(scope.row)"
              >删除
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 添加编辑 管理员弹框 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="addAdminTitle"
      :visible.sync="addAdminOpen"
      width="620px"
      append-to-body
    >
      <el-form
        ref="addAdminForm"
        :model="addAdminForm"
        :rules="addAdminRules"
        label-width="100px"
      >
        <el-form-item label="账号" prop="userName">
          <el-input
            v-if="addAdminTitle == `编辑分院管理员`"
            oninput="value=value.replace(/[^a-zA-Z_@0-9]/g, '')"
            disabled
            :value="addAdminForm.userName.slice(2)"
            @blur="checkUserName"
            placeholder="请输入账号"
          />
          <el-input
            v-else
            oninput="value=value.replace(/[^a-zA-Z_@0-9]/g, '')"
            v-model="addAdminForm.userName"
            @blur="checkUserName"
            placeholder="请输入账号"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="nickName">
          <el-input v-model="addAdminForm.nickName" placeholder="请输入名字"/>
        </el-form-item>

        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input
            v-if="addAdminTitle == `编辑分院管理员`"
            :disabled="addAdminTitle == `编辑分院管理员`"
            :value="addAdminForm.phoneNumber | regPhone"
            placeholder="请输入手机号码"
          />
          <el-input
            v-else
            v-model="addAdminForm.phoneNumber"
            placeholder="请输入手机号码"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick @click="addAdminOpen = false"
        >取 消
        </el-button
        >
        <el-button
          v-preventReClick
          type="primary"
          @click="addAdminFormsubmitForm"
        >确 定
        </el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { branchDisciplineIsLeader } from '@/api/disciplineGroup/disciplineGroup'
import { addPost_branchAdmin, getPost_branch, listPost_branchAdmin } from '@/api/schoolOrganization/organization'
import {
  getUser,
  getUserlnfoByUsemame,
  updateUserBranchManager,
  updateUserBranchManager_changeStatus,
  updateUserBranchManager_delete
} from '@/api/system/user'
import { checkPhonenot } from '@/utils/validate'

export default {
  name: 'branchDetial',
  props: {
    branchId: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    return {
      addAdminForm: {
        userId: undefined,
        nickName: undefined,
        phoneNumber: undefined,
        userName: '',
        roleIds: undefined
      },
      addAdminRules: {
        nickName: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '账号不能为空', trigger: 'blur' },
          { min: 6, message: '账号至少需要6位', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: false, validator: checkPhonenot, trigger: 'blur' }
        ]
      },
      userName: '',
      addAdminTitle: '',
      adminList: [],
      addAdminOpen: false,
      adminloading: false,
      loading: false,
      branchInfo: {
        content: ''
      }
    }
  },
  watch: {
    branchId: {
      handler() {
        this.getBranchDetial()
        this.getAdminList()
      },
      immediate: true
    }
  },
  mounted() {
  },
  computed: {
    renderedText() {
      return this.branchInfo.content
        ? this.branchInfo.content.replace(/\n/g, '<br>')
        : '--'
    }
  },
  methods: {
    async checkUserName() {
      if (
        this.addAdminTitle == '添加分院管理员' &&
        this.addAdminForm.userName
      ) {
        let res
        try {
          res = await getUserlnfoByUsemame(this.addAdminForm.userName)
        } finally {
          if (res.data) {
            this.$modal.msg(`${res.data.nickName}已存在`)
            this.addAdminForm.branchId = res.data.branchId
            this.addAdminForm.userId = res.data.userId
            this.addAdminForm.userName = res.data.account
            this.addAdminForm.nickName = res.data.nickName
            this.addAdminForm.phoneNumber = res.data.phoneNumber
          } else {
            this.form.userId = null
          }
        }
      }
    },
    async getAdminList() {
      this.adminloading = true
      let res = await listPost_branchAdmin({ branchId: this.branchId })
      if (res.code == 200) {
        this.adminloading = false
        this.adminList = res.rows
      }
    },
    /* 添加管理员 */
    handleAddAdmin() {
      this.addAdminTitle = `添加分院管理员`
      this.addAdminOpen = true
      this.resetAddAdmin()
    },
    /** 修改管理员 */
    async handleAdminUpdate(row) {
      this.addAdminTitle = `编辑分院管理员`
      this.addAdminOpen = true
      this.resetAddAdmin()
      let res = await getUser(row.userId)
      this.addAdminForm = res.data
      this.addAdminForm.roleIds = res.roleIds
      this.addAdminForm.phoneNumber = res.data.phoneNumber
        ? res.data.phoneNumber
        : null
      this.addAdminForm.userName = res.data.userName
    },
    // 删除管理员
    handleAdminDelete(row) {
      this.$confirm(`是否确认删除`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          updateUserBranchManager_delete(this.branchId, row.userId).then(
            () => {
              this.$modal.msgSuccess('操作成功')
              this.getAdminList()
            }
          )
        })
        .catch(() => {
        })
    },
    resetAddAdmin() {
      this.addAdminForm = {
        userId: undefined,
        nickName: undefined,
        phoneNumber: undefined,
        userName: '',
        roleIds: undefined
      }
      this.resetForm('addAdminForm')
    },
    addAdminFormsubmitForm() {
      this.$refs['addAdminForm'].validate((valid) => {
        console.log(valid)
        if (valid) {
          if (this.addAdminTitle == `编辑分院管理员`) {
            updateUserBranchManager(this.addAdminForm).then(() => {
              this.$modal.msgSuccess('修改成功')
              this.addAdminOpen = false
              this.getAdminList()
            })
          } else {
            this.addAdminForm.roleIds = [9]
            this.addAdminForm.schoolId = this.$store.getters.schoolId
            this.addAdminForm.branchId = this.branchId
            addPost_branchAdmin(this.addAdminForm).then(() => {
              this.$modal.msgSuccess('新增成功')
              this.addAdminOpen = false
              this.getAdminList()
            })
          }
        }
      })
    },
    // 停用 启用管理员
    handleAdminSwitch(row) {
      this.$confirm(`是否确认${row.status == 0 ? '停用' : '启用'}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          // 停用之前先判断是否为学科专业组组长
          branchDisciplineIsLeader({
            userId: row.userId
          }).then((res) => {
            if (res.data.isLeader == 1) {
              this.$confirm(
                `【${row.nickName}(${row.account})】为${res.data.disciplineGroupName}学科专业组组长，请先变更组长再停用账号`,
                '停用失败',
                {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  // showCancelButton: false,
                  type: 'warning'
                }
              )
                .then(async() => {
                })
                .catch(() => {
                })
            } else {
              let data = JSON.parse(JSON.stringify(row))
              data.status = row.status == 0 ? 1 : 0
              getUser(data.userId).then((res) => {
                data.roleIds = res.roleIds
                data.branchId = this.branchId
                delete data.phoneNumber
                updateUserBranchManager_changeStatus(data).then(() => {
                  this.$modal.msgSuccess('操作成功')
                  this.getAdminList()
                })
              })
            }
          })
        })
        .catch(() => {
        })
    },
    async getBranchDetial() {
      this.loading = true
      let res = await getPost_branch(this.branchId)
      if (res.code == 200) {
        this.loading = false
        this.branchInfo = res.data
      }
    }
  }
}
</script>

<style scoped lang="scss">
.content {
  width: 100%;
  display: flex;
  flex-direction: column;

  .content_title {
    color: #333333;
    font-size: 16px;
    font-weight: bold;
  }

  .main_content {
    margin-top: 10px;
    display: flex;
    align-items: center;

    &_left {
      padding: 10px;
      box-sizing: border-box;
      border-radius: 12px;
      background: white;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.08);

      .branch_pic {
        width: 320px;
        height: 200px;
        border-radius: 12px;
      }
    }

    &_right {
      flex: 1;
      margin-left: 10px;

      .content_lebal {
        width: 100%;
        color: #999999;
        display: flex;
        margin: 10px 0;

        .title {
          min-width: 88px;
        }

        .content_value {
          color: #333333;
        }

        .content_textarea {
          width: 500px;
          height: 80px;
          overflow: auto;
          color: #333333;
          word-wrap: break-word; /* 当单词超出容器宽度时自动换行 */
        }
      }
    }
  }
}
</style>
